// pages/order/add/index.js
import api from "../../../api/index";
const dayjs = require("dayjs");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    formData: {},

    showDay: false,
    showCoach: false,
    showTime: false,

    coachObj: {
      list: [],
      name: "coach_id",
    },

    pValue: 0,

    days: [],
    dayStr: "",
    currentDate: "",
    timeType: "",
    minDate: +dayjs().startOf("date"),
    maxDate: +dayjs().endOf("date"),

    isAdd: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.getCoachList();
  },
  getCoachList() {
    api.apiStoreMainCoachList().then((res) => {
      this.setData({
        "coachObj.list": res.data.list,
      });
    });
  },
  openPicker(e) {
    let key = "";
    let type = e.currentTarget.dataset.type;
    let formData = this.data.formData;
    switch (type) {
      case "coach":
        key = "showCoach";
        break;
      case "date":
        key = "showDay";
        break;
      case "sTime":
      case "eTime":
        key = "showTime";
        break;
    }
    if (type === "sTime" || type === "eTime") {
      this.setData({
        timeType: type,
      });
    }
    this.setData({
      [key]: true,
    });
  },
  onClose(e) {
    this.setData({
      showCoach: false,
      showDay: false,
      showTime: false,
    });
  },
  getValue(e) {
    let { coachObj } = this.data;
    let data = {};
    let name = e.detail.type;
    let value = e.detail.value;
    data[`formData.${name}`] = value;
    if (name === "coach_id") {
      data["formData.coachLabel"] = coachObj.list.find(
        (i) => i.coach_id === value
      ).nickname;
    }
    this.setData(data);
    this.onClose();
  },
  getDateValue(e) {
    let { formData } = this.data;
    let data = {};
    if (formData.day === "single") {
      data["formData.site_date"] = dayjs(e.detail).format("YYYY-MM-DD");
    } else {
      data["formData.site_date"] = e.detail
        .map((i) => dayjs(i).format("YYYY-MM-DD"))
        .join(",");
    }
    data["formData.dayLabel"] =
      formData.day === "single"
        ? data["formData.site_date"]
        : e.detail.length === 1
        ? data["formData.site_date"]
        : `已选择${e.detail.length}个日期`;
    this.setData(data);
    this.onClose();
  },
  getTimeVal(e) {
    this.setData({
      currentDate: e.detail,
    });
  },
  getTime(e) {
    let { timeType, currentDate } = this.data;
    this.setData({
      [`formData.${
        timeType === "sTime" ? "start_time" : "end_time"
      }`]: currentDate,
    });
    this.onClose();
  },
  onAdd() {
    let { formData, isAdd } = this.data;
    if (isAdd) return;
    this.setData({ isAdd: true });
    if (
      !formData.coach_id ||
      !formData.site_date ||
      !formData.start_time ||
      !formData.end_time
    ) {
      wx.showToast({
        title: "必填参数不能为空",
        icon: "none",
      });
      this.setData({ isAdd: false });
      return;
    }
    if (
      +dayjs()
        .startOf("date")
        .add(formData.start_time.split(":")[0], "hour")
        .add(formData.start_time.split(":")[1], "minute") >=
      +dayjs()
        .startOf("date")
        .add(formData.end_time.split(":")[0], "hour")
        .add(formData.end_time.split(":")[1], "minute")
    ) {
      wx.showToast({
        title: "开始时间大于结束时间",
        icon: "none",
      });
      this.setData({ isAdd: false });
      return;
    }

    let param = {
      coach_id: formData.coach_id,
      site_date: formData.site_date,
      start_time: formData.start_time,
      end_time: formData.end_time,
    };
    api
      .apiStoreAddSite(param)
      .then((res) => {
        if (res.code === 1) {
          wx.showToast({
            title: "添加成功",
            icon: "none",
          });
          setTimeout((_) => {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.init) {
              prevPage.init();
            }
            wx.navigateBack();
          }, 2500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      })
      .finally((_) => {
        this.setData({ isAdd: false });
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
